﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Web;
using System.Net.Security;
using System.Globalization;

namespace UtilityLibrary.Http
{
	public delegate void ProgressChangeHandler(Int64 total, Int64 complated);
	public delegate void ResponseConnectedHandler();

	public sealed class HttpRequestHolder
	{
		/// <summary>
		/// 中文编码转换
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static String Encode(String value, Encoding encoding)
		{
			return HttpUtility.UrlEncode(value, encoding);
		}

		/// <summary>
		/// 编码转中文
		/// </summary>
		/// <param name="value"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static String Decode(String value, Encoding encoding)
		{
			return HttpUtility.UrlDecode(value, encoding);
		}

		/// <summary>
		/// 中文编码转换
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public String Encode(String value)
		{
			return HttpUtility.UrlEncode(value, Encoding);
		}

		/// <summary>
		/// 编码转中文
		/// </summary>
		/// <param name="value"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public String Decode(String value)
		{
			return HttpUtility.UrlDecode(value, Encoding);
		}

		/// <summary>
		/// 证书
		/// </summary>
		private X509Certificate2 _cert;
		public X509Certificate2 Cert { get { return _cert; } }

		/// <summary>
		/// 保存cookie的模式
		/// </summary>
		private CookieModel _cookieModel;

		private CookieCollection _cookies;
		/// <summary>
		/// 当前Cookie集合
		/// </summary>
		public CookieCollection Cookies
		{
			get
			{
				return _cookies;
			}
		}

		/// <summary>
		/// Cookie容器
		/// </summary>
		public CookieContainer CookieContainer { get; set; }

		/// <summary>
		/// 请求过程中的Domain
		/// </summary>
		public String CookieDomain { get; set; }

		private Encoding _encoding;
		/// <summary>
		/// 获取编码格式
		/// </summary>
		public Encoding Encoding
		{
			get { return _encoding; }
		}

		private Int32 _timeout;
		/// <summary>
		/// 超时时间
		/// </summary>
		public void SetTimeout(Int32 timeout)
		{
			_timeout = timeout;
		}

		/// <summary>
		/// 请求sessionid
		/// </summary>
		public String DesSessionId { get; set; }

		/// <summary>
		/// 请求过程中保持的参数
		/// </summary>
		public Object ParamaterHolder { get; set; }

		private HttpRecordCollection _log;
		/// <summary>
		/// 日志
		/// </summary>
		public HttpRecordCollection Log
		{
			get
			{
				return _log;
			}
		}

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="thumbprint">证书指纹字符串</param>
		public HttpRequestHolder(String thumbprint)
		{
			//初始化Cookie容器
			CookieContainer = new CookieContainer();
			_cookies = new CookieCollection();

			//创建证书
			if (!String.IsNullOrEmpty(thumbprint)) _cert = CertCreater.GetCertByThumbprint(thumbprint);

			//设置编码为默认编码
			_encoding = Encoding.Default;
			_cookieModel = CookieModel.CookieContainer;
			_timeout = 300000;
			_log = new HttpRecordCollection();
		}

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="thumbprint">证书指纹字符串</param>
		/// <param name="encoding">编码格式</param>
		public HttpRequestHolder(String thumbprint, Encoding encoding)
			: this(thumbprint)
		{
			//设置编码格式
			this._encoding = encoding;
		}

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="thumbprint">证书指纹字符串</param>
		/// <param name="encoding">编码格式</param>
		/// <param name="cModel">保存cookie模式</param>
		public HttpRequestHolder(String thumbprint, Encoding encoding, CookieModel cModel, String domain)
			: this(thumbprint, encoding)
		{
			this._cookieModel = cModel;
			this.CookieDomain = domain;
		}

		/// <summary>
		/// Get方式获取请求的响应
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <returns>响应对象</returns>
		public HttpWebResponse Get(HttpWebRequest request)
		{
			//添加cookie
			request.CookieContainer = CookieContainer;
			switch (_cookieModel)
			{
				case CookieModel.CookieContainer:
					request.CookieContainer = CookieContainer;
					break;
				case CookieModel.CookieCollection:
					request.CookieContainer = new CookieContainer();
					foreach (Cookie c in _cookies)
					{
						request.CookieContainer.Add(request.RequestUri, new Cookie(c.Name, c.Value, c.Path, CookieDomain));
					}
					break;
				default:
					break;
			}

			ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
			ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
			//添加证书
			if (_cert != null)
			{
				request.ClientCertificates.Add(_cert);
			}

			//设置请求方式
			request.Method = "GET";

			//获得响应并设置Cookies
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			_cookies.Add(response.Cookies);

			//返回响应
			return response;
		}

		/// <summary>
		/// Get方式获得请求响应的字符串
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <returns>响应字符串</returns>
		public String GetResponseString(HttpWebRequest request)
		{
			StringBuilder returnValue = new StringBuilder();

			//获取请求的响应
			HttpWebResponse response = Get(request);

			try
			{
				//创建流对象，读取响应流，生成字符串
				StreamReader sr = new StreamReader(response.GetResponseStream(), _encoding);
				returnValue.Append(sr.ReadToEnd());
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "GET";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.ResponseContent = returnValue.ToString();
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				//关闭响应流
				response.Close();
			}

			//返回响应字符串
			return returnValue.ToString();
		}

		/// <summary>
		/// Get方式获得请求响应的Html正文对象
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <returns>响应的Html正文</returns>
		public HtmlContext GetResponseHtmlContext(HttpWebRequest request)
		{
			return new HtmlContext(GetResponseString(request), request.RequestUri);
		}

		/// <summary>
		/// Get方式获得请求的响应并保存为文件
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="fileName">保存文件路径</param>
		public void GetSaveFile(HttpWebRequest request, String fileName)
		{
			//获取请求的响应
			HttpWebResponse response = Get(request);
			Stream sr = null;
			FileStream fs = null;
			try
			{
				//创建流对象
				sr = response.GetResponseStream();
				//创建文件流对象
				fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

				//循环读取流保存到文件
				byte[] buffer = new byte[1024];
				int bytesRead = sr.Read(buffer, 0, buffer.Length);
				while (bytesRead > 0)
				{
					fs.Write(buffer, 0, bytesRead);
					bytesRead = sr.Read(buffer, 0, buffer.Length);
				}

			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "GET";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				if (fs != null) fs.Close();
				if (sr != null) sr.Close();
				response.Close();
			}
		}

		public void GetSaveFile(HttpWebRequest request, String fileName, ResponseConnectedHandler asyncResponseConnected, ProgressChangeHandler asyncProgressChanged)
		{
			//获取请求的响应
			HttpWebResponse response = Get(request);

			if (asyncResponseConnected != null) asyncResponseConnected();

			Stream sr = null;
			FileStream fs = null;

			try
			{
				//创建流对象
				sr = response.GetResponseStream();
				//创建文件流对象
				fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

				Int64 length = response.ContentLength;
				//循环读取流保存到文件
				byte[] buffer = new byte[1024];
				int bytesRead = sr.Read(buffer, 0, buffer.Length);
				int times = 0;
				while (bytesRead > 0)
				{
					fs.Write(buffer, 0, bytesRead);
					if (asyncProgressChanged != null)
					{
						if (length == -1)
						{
							int complated = times <= 98 ? times + 1 : 99;
							asyncProgressChanged(100, complated);
						}
						else
						{
							int complated = buffer.Length * times + bytesRead;
							asyncProgressChanged(length, complated);
						}

					}
					times++;
					bytesRead = sr.Read(buffer, 0, buffer.Length);
				}
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "GET";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				if (fs != null) fs.Close();
				if (sr != null) sr.Close();
				response.Close();
			}
		}

		/// <summary>
		/// Post方式获得请求的响应
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字符串</param>
		/// <returns>响应对象</returns>
		public HttpWebResponse Post(HttpWebRequest request, String param)
		{
			//添加cookie
			request.CookieContainer = CookieContainer;
			switch (_cookieModel)
			{
				case CookieModel.CookieContainer:
					request.CookieContainer = CookieContainer;
					break;
				case CookieModel.CookieCollection:
					request.CookieContainer = new CookieContainer();
					foreach (Cookie c in _cookies)
					{
						request.CookieContainer.Add(request.RequestUri, new Cookie(c.Name, c.Value, c.Path, CookieDomain));
					}
					break;
				default:
					break;
			}

			ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
			ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
			//添加证书
			if (_cert != null)
			{
				request.ClientCertificates.Add(_cert);
			}

			//设置请求方式
			request.Method = "POST";
			request.Timeout = _timeout;
			if (!String.IsNullOrEmpty(param)) SetPostData(request, param);

			//获得响应并设置Cookies
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			_cookies.Add(response.Cookies);

			//返回响应
			return response;
		}

		/// <summary>
		/// Post方式获得请求响应
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="paramaters">参数字典</param>
		/// <returns>响应对象</returns>
		public HttpWebResponse Post(HttpWebRequest request, Dictionary<String, String> paramaters)
		{
			return Post(request, ParamatersToString(paramaters));
		}

		/// <summary>
		/// 异步处理Post请求
		/// </summary>
		/// <param name="request"></param>
		/// <param name="param"></param>
		/// <param name="async"></param>
		public void AsyncPost(HttpWebRequest request, String param, AsyncCallback async)
		{
			//添加cookie
			request.CookieContainer = CookieContainer;
			switch (_cookieModel)
			{
				case CookieModel.CookieContainer:
					request.CookieContainer = CookieContainer;
					break;
				case CookieModel.CookieCollection:
					request.CookieContainer = new CookieContainer();
					foreach (Cookie c in _cookies)
					{
						request.CookieContainer.Add(request.RequestUri, new Cookie(c.Name, c.Value, c.Path, CookieDomain));
					}
					break;
				default:
					break;
			}

			ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
			ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
			//添加证书
			if (_cert != null)
			{
				request.ClientCertificates.Add(_cert);
			}

			//设置请求方式
			request.Method = "POST";
			request.Timeout = _timeout;
			if (!String.IsNullOrEmpty(param)) SetPostData(request, param);

			//开始执行异步Post请求
			request.BeginGetResponse(async, request);
		}

		public void AsyncPost(HttpWebRequest request, Dictionary<String, String> paramaters, AsyncCallback async)
		{
			AsyncPost(request, ParamatersToString(paramaters), async);
		}

		/// <summary>
		/// Post方式获得请求的响应流
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字符串</param>
		/// <returns>响应流</returns>
		public MemoryStream PostResponseStream(HttpWebRequest request, String param)
		{
			MemoryStream msr = null;

			//获取请求的响应
			HttpWebResponse response = Post(request, param);
			try
			{
				//创建流对象，读取响应流，生成字符串
				Stream sr = response.GetResponseStream();
				msr = new MemoryStream();

				byte[] buffer = new byte[1024];
				int count = sr.Read(buffer, 0, 1024);
				while (count > 0)
				{
					msr.Write(buffer, 0, 1024);
					count = sr.Read(buffer, 0, 1024);
				}
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(StringToParamaters(param));
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				//关闭响应流
				response.Close();
			}

			return msr;
		}

		/// <summary>
		/// Post方式获得请求的响应流
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字典</param>
		/// <returns>响应流</returns>
		public MemoryStream PostResponseStream(HttpWebRequest request, Dictionary<String, String> paramaters)
		{
			return PostResponseStream(request, ParamatersToString(paramaters));
		}

		/// <summary>
		/// Post方式获得请求的响应并保存为文件
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字符串</param>
		/// <param name="fileName">保存文件路径</param>
		public void PostResponseSaveFile(HttpWebRequest request, String param, String fileName)
		{
			//获取请求的响应
			HttpWebResponse response = Post(request, param);
			Stream sr = null;
			FileStream fs = null;
			try
			{
				//创建流对象
				sr = response.GetResponseStream();
				//创建文件流对象
				fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

				//循环读取流保存到文件
				byte[] buffer = new byte[1024];
				int bytesRead = sr.Read(buffer, 0, buffer.Length);
				while (bytesRead > 0)
				{
					fs.Write(buffer, 0, bytesRead);
					bytesRead = sr.Read(buffer, 0, buffer.Length);
				}
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(StringToParamaters(param));
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				if (fs != null) fs.Close();
				if (sr != null) sr.Close();
				response.Close();
			}
		}

		/// <summary>
		/// 方式获得请求的响应并保存为文件
		/// </summary>
		/// <param name="request"></param>
		/// <param name="param"></param>
		/// <param name="fileName"></param>
		/// <param name="asyncResponseConnected"></param>
		/// <param name="asyncProgressChanged"></param>
		public void PostResponseSaveFile(HttpWebRequest request, String param, String fileName, ResponseConnectedHandler asyncResponseConnected, ProgressChangeHandler asyncProgressChanged)
		{
			//获取请求的响应
			HttpWebResponse response = Post(request, param);
			if (asyncResponseConnected != null) asyncResponseConnected();

			Stream sr = null;
			FileStream fs = null;

			try
			{
				//创建流对象
				sr = response.GetResponseStream();
				//创建文件流对象
				fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

				Int64 length = response.ContentLength;
				//循环读取流保存到文件
				byte[] buffer = new byte[1024];
				int bytesRead = sr.Read(buffer, 0, buffer.Length);
				int times = 0;
				while (bytesRead > 0)
				{
					fs.Write(buffer, 0, bytesRead);
					if (asyncProgressChanged != null)
					{
						if (length == -1)
						{
							int complated = times <= 98 ? times + 1 : 99;
							asyncProgressChanged(100, complated);
						}
						else
						{
							int complated = buffer.Length * times + bytesRead;
							asyncProgressChanged(length, complated);
						}

					}
					times++;
					bytesRead = sr.Read(buffer, 0, buffer.Length);
				}
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(StringToParamaters(param));
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				if (fs != null) fs.Close();
				if (sr != null) sr.Close();
				response.Close();
			}
		}

		/// <summary>
		/// Post方式获得请求的响应并保存为文件
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字典</param>
		/// <param name="fileName">保存文件路径</param>
		public void PostResponseSaveFile(HttpWebRequest request, Dictionary<String, String> paramaters, String fileName)
		{
			PostResponseSaveFile(request, ParamatersToString(paramaters), fileName);
		}

		/// <summary>
		/// Post方式获得请求的响应并保存为文件
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="fileName"></param>
		/// <param name="asyncResponseConnected"></param>
		/// <param name="asyncProgressChanged"></param>
		public void PostResponseSaveFile(HttpWebRequest request, Dictionary<String, String> paramaters, String fileName, ResponseConnectedHandler asyncResponseConnected, ProgressChangeHandler asyncProgressChanged)
		{
			PostResponseSaveFile(request, ParamatersToString(paramaters), fileName, asyncResponseConnected, asyncProgressChanged);
		}

		/// <summary>
		/// Post方式获得请求的响应字符串
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字符串</param>
		/// <returns>响应字符串</returns>
		public String PostResponseString(HttpWebRequest request, String param)
		{
			StringBuilder returnValue = new StringBuilder();

			//获取请求的响应
			HttpWebResponse response = Post(request, param);
			try
			{
				//创建流对象，读取响应流，生成字符串
				StreamReader sr = new StreamReader(response.GetResponseStream(), _encoding);
				returnValue.Append(sr.ReadToEnd());
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(StringToParamaters(param));
				record.ResponseContent = returnValue.ToString();
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				//关闭响应流
				response.Close();
			}

			//获得并返回响应
			return returnValue.ToString();
		}

		/// <summary>
		/// Post方式获得请求的响应字符串
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字典</param>
		/// <returns>响应字符串</returns>
		public String PostResponseString(HttpWebRequest request, Dictionary<String, String> paramaters)
		{
			return PostResponseString(request, ParamatersToString(paramaters));
		}

		/// <summary>
		/// Post方式获得请求的响应Html正文对象
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字符串</param>
		/// <returns>响应Html正文</returns>
		public HtmlContext PostResponseHtmlContext(HttpWebRequest request, String param)
		{
			return new HtmlContext(PostResponseString(request, param), request.RequestUri);
		}

		/// <summary>
		/// Post方式获得请求的响应Html正文对象
		/// </summary>
		/// <param name="request">请求对象</param>
		/// <param name="param">参数字典</param>
		/// <returns>响应Html正文</returns>
		public HtmlContext PostResponseHtmlContext(HttpWebRequest request, Dictionary<String, String> paramaters)
		{
			return PostResponseHtmlContext(request, ParamatersToString(paramaters));
		}

		/// <summary>
		/// 上传文件获得响应对象
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="FilePath"></param>
		/// <returns></returns>
		public HttpWebResponse UpLoad(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName)
		{
			//添加cookie
			request.CookieContainer = CookieContainer;
			switch (_cookieModel)
			{
				case CookieModel.CookieContainer:
					request.CookieContainer = CookieContainer;
					break;
				case CookieModel.CookieCollection:
					request.CookieContainer = new CookieContainer();
					foreach (Cookie c in _cookies)
					{
						request.CookieContainer.Add(request.RequestUri, new Cookie(c.Name, c.Value, c.Path, CookieDomain));
					}
					break;
				default:
					break;
			}

			//添加证书
			if (_cert != null)
			{
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
				request.ClientCertificates.Add(_cert);
			}

			//设置请求方式
			request.Method = "POST";
			//request.Timeout = _timeout;

			SetUpLoadData(request, paramaters, filePath, filePName);

			//获得响应并设置Cookies
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			_cookies.Add(response.Cookies);

			//返回响应
			return response;
		}

		/// <summary>
		/// 上传文件获得响应对象
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="FilePath"></param>
		/// <returns></returns>
		public HttpWebResponse UpLoad(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName, byte[] fileData)
		{
			//添加cookie
			request.CookieContainer = CookieContainer;
			switch (_cookieModel)
			{
				case CookieModel.CookieContainer:
					request.CookieContainer = CookieContainer;
					break;
				case CookieModel.CookieCollection:
					request.CookieContainer = new CookieContainer();
					foreach (Cookie c in _cookies)
					{
						request.CookieContainer.Add(request.RequestUri, new Cookie(c.Name, c.Value, c.Path, CookieDomain));
					}
					break;
				default:
					break;
			}

			//添加证书
			if (_cert != null)
			{
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
				request.ClientCertificates.Add(_cert);
			}

			//设置请求方式
			request.Method = "POST";
			//request.Timeout = _timeout;

			SetUpLoadData(request, paramaters, filePath, filePName, fileData);

			//获得响应并设置Cookies
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			_cookies.Add(response.Cookies);

			//返回响应
			return response;
		}

		/// <summary>
		/// 上传文件获得响应字符串
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		/// <returns></returns>
		public String UpLoadResponseString(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName)
		{
			StringBuilder returnValue = new StringBuilder();

			//获取请求的响应
			HttpWebResponse response = UpLoad(request, paramaters, filePath, filePName);
			try
			{
				//创建流对象，读取响应流，生成字符串
				StreamReader sr = new StreamReader(response.GetResponseStream(), _encoding);
				returnValue.Append(sr.ReadToEnd());
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(paramaters);
				record.ResponseContent = returnValue.ToString();
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				//关闭响应流
				response.Close();
			}

			//获得并返回响应
			return returnValue.ToString();
		}

		/// <summary>
		/// 上传文件获得响应字符串
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		/// <returns></returns>
		public String UpLoadResponseString(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName, byte[] fileData)
		{
			StringBuilder returnValue = new StringBuilder();

			//获取请求的响应
			HttpWebResponse response = UpLoad(request, paramaters, filePath, filePName, fileData);
			try
			{
				//创建流对象，读取响应流，生成字符串
				StreamReader sr = new StreamReader(response.GetResponseStream(), _encoding);
				returnValue.Append(sr.ReadToEnd());
			}
			finally
			{
				//记录请求过程中的相关信息
				HttpRecord record = new HttpRecord();
				record.Link = request.RequestUri.AbsoluteUri;
				record.Method = "POST";
				record.RequestHeaders.Add(request.Headers);
				record.ResponseHeaders.Add(response.Headers);
				record.SetParamaters(paramaters);
				record.ResponseContent = returnValue.ToString();
				record.RecordTime = DateTime.Now;
				Log.Add(record);

				//关闭响应流
				response.Close();
			}

			//获得并返回响应
			return returnValue.ToString();
		}

		/// <summary>
		/// 上传文件获得响应Html正文对象
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		/// <returns></returns>
		public HtmlContext UpLoadResponseHtmlContext(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName)
		{
			return new HtmlContext(UpLoadResponseString(request, paramaters, filePath, filePName), request.RequestUri);
		}

		/// <summary>
		/// 上传文件获得响应Html正文对象
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		/// <returns></returns>
		public HtmlContext UpLoadResponseHtmlContext(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName, byte[] fileData)
		{
			return new HtmlContext(UpLoadResponseString(request, paramaters, filePath, filePName, fileData), request.RequestUri);
		}

		/// <summary>
		/// 提交表单
		/// </summary>
		/// <param name="formCtx">表单对象</param>
		/// <returns></returns>
		public String Submit(HtmlFormContext formCtx)
		{
			if (String.IsNullOrEmpty(formCtx.Html)) throw new HtmlFormContextException("表单未初始化");
			if (String.IsNullOrEmpty(formCtx.Action)) throw new HtmlFormContextException("未能提取表单提交地址");
			if (formCtx.Action.StartsWith("http", StringComparison.OrdinalIgnoreCase)) throw new HtmlFormContextException("匹配到的提交地址不包含域名信息");

			//根据表单信息创建request并提交返回响应
			HttpWebRequest request = null;
			switch (formCtx.Method)
			{
				//Get方式的处理过程
				case "GET":
					String reqUrl = formCtx.Action;
					String paramString = ParamatersToString(formCtx.Params, _encoding);
					if (!String.IsNullOrEmpty(paramString)) reqUrl = reqUrl + "?" + paramString;
					try { request = DefaultRequest.FromString(formCtx.Action); }
					catch { throw new HtmlFormContextException("匹配到的提交地址无法转换为请求地址"); }
					if (formCtx.RefererUrl != null) request.Referer = formCtx.RefererUrl.AbsoluteUri;
					return GetResponseString(request);
				//Post方式的处理过程
				case "POST":
					try { request = DefaultRequest.FromString(formCtx.Action); }
					catch { throw new HtmlFormContextException("匹配到的提交地址无法转换为请求地址"); }
					if (formCtx.RefererUrl != null) request.Referer = formCtx.RefererUrl.AbsoluteUri;
					return PostResponseString(request, formCtx.Params);
				//其他抛出异常
				default: throw new HtmlFormContextException("匹配到的提交方式错误");
			}
		}

		/// <summary>
		/// 提交表单并返回html正文对象
		/// </summary>
		/// <param name="formCtx">表单对象</param>
		/// <returns></returns>
		public HtmlContext SubmitHtmlContext(HtmlFormContext formCtx)
		{
			return new HtmlContext(Submit(formCtx), new Uri(formCtx.Action));
		}

		/// <summary>
		/// 创建参数字符串
		/// </summary>
		/// <param name="paramaters">参数字典</param>
		/// <returns>字符串</returns>
		public static String ParamatersToString(Dictionary<String, String> paramaters)
		{
			StringBuilder returnValue = new StringBuilder();

			//循环字典，将参数集合转换成字符串
			foreach (String key in paramaters.Keys)
			{
				returnValue.Append(key);
				returnValue.Append("=");
				returnValue.Append(paramaters[key]);
				returnValue.Append("&");
			}

			//删除最后一个&连接符号
			if (returnValue.ToString().EndsWith("&", StringComparison.OrdinalIgnoreCase)) returnValue.Remove(returnValue.Length - 1, 1);

			return returnValue.ToString();
		}

		/// <summary>
		/// 创建参数字符串
		/// </summary>
		/// <param name="paramaters">参数字典</param>
		/// <returns>字符串</returns>
		public static String ParamatersToString(Dictionary<String, String> paramaters, Encoding encoding)
		{
			StringBuilder returnValue = new StringBuilder();

			//循环字典，将参数集合转换成字符串
			foreach (String key in paramaters.Keys)
			{
				returnValue.Append(Encode(key, encoding));
				returnValue.Append("=");
				returnValue.Append(Encode(paramaters[key], encoding));
				returnValue.Append("&");
			}

			//删除最后一个&连接符号
			if (returnValue.ToString().EndsWith("&", StringComparison.OrdinalIgnoreCase)) returnValue.Remove(returnValue.Length - 1, 1);

			return returnValue.ToString();
		}

		/// <summary>
		/// 将参数串分解成参数集合
		/// </summary>
		/// <param name="param">参数串</param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static Dictionary<String, String> StringToParamaters(String param)
		{
			Dictionary<String, String> returnValue = new Dictionary<String, String>();

			//分隔字符串将参数加入集合
			foreach (String keyValues in param.Split(new Char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
			{
				returnValue.Add(keyValues.Substring(0, keyValues.IndexOf('=')), keyValues.Substring(keyValues.IndexOf('=') + 1, keyValues.Length - keyValues.IndexOf('=') - 1));
			}

			return returnValue;
		}

		/// <summary>
		/// 将参数串分解成参数集合
		/// </summary>
		/// <param name="param">参数串</param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static Dictionary<String, String> StringToParamaters(String param, Encoding encoding)
		{
			Dictionary<String, String> returnValue = new Dictionary<String, String>();

			//分隔字符串将参数加入集合
			foreach (String keyValues in param.Split(new Char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
			{
				returnValue.Add(keyValues.Substring(0, keyValues.IndexOf('=')), Decode(keyValues.Substring(keyValues.IndexOf('=') + 1, keyValues.Length - keyValues.IndexOf('=') - 1), encoding));
			}

			return returnValue;
		}

		/// <summary>
		/// 设置Post请求参数
		/// </summary>
		/// <param name="request"></param>
		/// <param name="data"></param>
		private void SetPostData(HttpWebRequest request, String data)
		{
			//获取字符串字节值
			byte[] param = _encoding.GetBytes(data);

			//写入请求流
			Stream requestStream = request.GetRequestStream();
			requestStream.Write(param, 0, param.Length);
			requestStream.Close();
		}

		/// <summary>
		/// 设置上传文件请求的参数
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		private void SetUpLoadData(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName)
		{
			//设置请求参数的分界字符串
			string strBoundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.CurrentCulture);
			request.ContentType = "multipart/form-data; boundary=" + strBoundary;

			MemoryStream postStream = new MemoryStream();
			BinaryWriter postWriter = new BinaryWriter(postStream);

			foreach (String key in paramaters.Keys)
			{
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}\r\n", strBoundary)));
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "Content-Disposition: form-data; name=\"{0}\"\r\n", key)));
				postWriter.Write(_encoding.GetBytes("\r\n"));
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "{0}\r\n", paramaters[key])));
			}

			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}\r\n", strBoundary)));
			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", filePName, filePath)));
			postWriter.Write(_encoding.GetBytes("Content-Type: application/vnd.ms-excel \r\n"));
			postWriter.Write(_encoding.GetBytes("\r\n"));
			if (File.Exists(filePath))
			{
				postWriter.Write(File.ReadAllBytes(filePath));
			}
			postWriter.Write(_encoding.GetBytes("\r\n"));
			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}--\r\n", strBoundary)));

			request.ContentLength = postStream.Length;
			Stream requestStream = request.GetRequestStream();
			postStream.WriteTo(requestStream);
			postWriter.Close();
			postStream.Close();
			requestStream.Close();
		}

		/// <summary>
		/// 设置上传文件请求的参数
		/// </summary>
		/// <param name="request"></param>
		/// <param name="paramaters"></param>
		/// <param name="filePath"></param>
		/// <param name="filePName"></param>
		private void SetUpLoadData(HttpWebRequest request, Dictionary<String, String> paramaters, String filePath, String filePName, byte[] fileData)
		{
			//设置请求参数的分界字符串
			string strBoundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.CurrentCulture);
			request.ContentType = "multipart/form-data; boundary=" + strBoundary;

			MemoryStream postStream = new MemoryStream();
			BinaryWriter postWriter = new BinaryWriter(postStream);

			foreach (String key in paramaters.Keys)
			{
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}\r\n", strBoundary)));
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "Content-Disposition: form-data; name=\"{0}\"\r\n", key)));
				postWriter.Write(_encoding.GetBytes("\r\n"));
				postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "{0}\r\n", paramaters[key])));
			}

			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}\r\n", strBoundary)));
			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", filePName, filePath)));
			postWriter.Write(_encoding.GetBytes("Content-Type: application/vnd.ms-excel \r\n"));
			postWriter.Write(_encoding.GetBytes("\r\n"));
			if (fileData != null)
			{
				postWriter.Write(fileData);
			}
			postWriter.Write(_encoding.GetBytes("\r\n"));
			postWriter.Write(_encoding.GetBytes(String.Format(CultureInfo.CurrentCulture, "--{0}--\r\n", strBoundary)));

			request.ContentLength = postStream.Length;
			Stream requestStream = request.GetRequestStream();
			postStream.WriteTo(requestStream);
			postWriter.Close();
			postStream.Close();
			requestStream.Close();
		}

		/// <summary>
		/// 证书相关，安全策略模式
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="certificate"></param>
		/// <param name="chain"></param>
		/// <param name="errors"></param>
		/// <returns></returns>
		private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
		{
			return true;
		}
	}
}